import React, { Component } from 'react'

import { Query, graphql } from 'react-apollo'
import gql from 'graphql-tag'

import { withNavigation } from 'react-navigation'
import {
  FlatList,
  StyleSheet,
  Text,
  TouchableOpacity,
  View,
} from 'react-native'
import { SearchBar } from 'antd-mobile'
import { Icon, IconButton } from '../components'

import store from '../store'

const QUERY_ITEMS = gql`
  query($search: String!) {
    allItems(
      filter: { OR: [{ title_contains: $search }, { intro_contains: $search }] }
    ) {
      id
      title
      intro
      price
      tags
      images
      createdAt
      updatedAt
    }
  }
`

const QUERY_ITEMS_BY_CATEGORY = gql`
  query($search: String!, $categoryId: ID!) {
    allItems(
      filter: {
        AND: [
          { OR: [{ title_contains: $search }, { intro_contains: $search }] }
          { category: { id: $categoryId } }
        ]
      }
    ) {
      id
      title
      intro
      price
      tags
      images
      createdAt
      updatedAt
    }
  }
`

export class ItemsScreen extends Component {
  render = () =>
    (({ navigation }) => (
      <View style={{ flex: 1, backgroundColor: 'white' }}>
        <SearchBar
          placeholder="Search"
          defaultValue={navigation.getParam('search')}
          onSubmit={search =>
            navigation.replace('Items', { ...navigation.params, search })
          }
        />
        <Query
          query={
            navigation.getParam('categoryId')
              ? QUERY_ITEMS_BY_CATEGORY
              : QUERY_ITEMS
          }
          variables={{
            search: navigation.getParam('search', ''),
            categoryId: navigation.getParam('categoryId'),
          }}
          fetchPolicy="network-only"
        >
          {({ loading, refetch, data: { ['allItems']: items } = {} }) =>
            !loading && (
              <Items data={items || []} loading={loading} onRefresh={refetch} />
            )
          }
        </Query>
      </View>
    ))(this.props)
}

export const Items = ({ data, loading, onRefresh }) => (
  <FlatList
    data={data}
    refreshing={loading}
    onRefresh={onRefresh}
    keyExtractor={x => x.id}
    renderItem={({ item }) => <ItemsItem data={item} />}
  />
)

const ItemsItem = withNavigation(({ data, navigation }) => (
  <TouchableOpacity
    style={styles.container}
    onPress={() => navigation.navigate('Item', { id: data.id })}
  >
    <View style={styles.content}>
      <Text style={styles.name}>{data.title}</Text>
    </View>
    <View style={styles.offside}>
      <Icon name="arrow-forward" />
    </View>
  </TouchableOpacity>
))

const styles = StyleSheet.create({
  container: {
    flexDirection: 'row',
    alignItems: 'center',
    borderBottomWidth: 1,
    borderBottomColor: 'whitesmoke',
  },
  content: {
    flex: 1,
    flexDirection: 'row',
    paddingVertical: 20,
  },
  name: {
    marginLeft: 15,
  },
  offside: {
    paddingHorizontal: 15,
  },
})
